﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Photo.Respository;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Photo.Web.Core.Setup
{
    /// <summary>
    /// sqlsugar扩展集成
    /// </summary>
    public static class SqlsugarSetup
    {
        /// <summary>
        /// 添加sqlsugar扩展集成
        /// </summary>
        /// <param name="services"></param>
        /// <param name="conStr"></param>
        public static void AddSqlsugarSetup(this IServiceCollection services, string conStr)
        {
            var configConnection = new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = conStr,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,//从特性读取主键自增信息
            };

            SqlSugarScope sqlSugar = new SqlSugarScope(configConnection);
            sqlSugar.Ado.CommandTimeOut = 10;//单位秒，超时

            sqlSugar.QueryFilter.Add(new SqlFilterItem//单表全局过滤器
            {
                FilterValue = _filterDb =>
                {
                    return new SqlFilterResult()
                    {
                        Sql = " IsDeleted!=1"
                    };
                },
                IsJoinQuery = false
            })
            .Add(new SqlFilterItem//多表全局过滤器
            {
                FilterValue = _filterDb =>
                {
                    return new SqlFilterResult()
                    {
                        Sql = " f.IsDeleted=0"
                    };
                },
                IsJoinQuery = true
            });

            services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));//仓储注册
            services.AddUnitOfWork<SqlSugarUnitOfWork>();//启用sqlsugar工作单元(仓储事务)
        }
    }
}
